﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using DunSilverlight.ViewModel;
using DunSilverlight.Comm;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
using System.Reflection;

namespace DunSilverlight.Views
{
    public partial class ExcelPage : Page
    {
        ReportService.ReportServiceClient ser = new ReportService.ReportServiceClient();
        BankService.BankServiceClient bankSer = new BankService.BankServiceClient();
        UserService.UserServiceClient userSer = new UserService.UserServiceClient();
        public ExcelPage()
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Report_Excel))
            {
                if (AppGlobal.CurrentUser != null)
                    Tools.ShowMessage("该用户没有权限查看 ", "", false);
                return;
            }
            InitializeComponent();
            timePeriod.SelectedDate = DateTime.Now;
            timePeriod.Culture.DateTimeFormat.ShortDatePattern = "yyyy-MM";

            bankSer.GetListByHQLCompleted += new EventHandler<BankService.GetListByHQLCompletedEventArgs>(bankSer_GetListByHQLCompleted);
            loadBank();

            userSer.GetListBySQLCompleted += new EventHandler<UserService.GetListBySQLCompletedEventArgs>(userSer_GetListBySQLCompleted);
            loadOper();

            ser.ExcelPageCompleted += new EventHandler<ReportService.ExcelPageCompletedEventArgs>(ser_ExcelPageCompleted);

            ser.DunStateCompleted += new EventHandler<ReportService.DunStateCompletedEventArgs>(ser_DunStateCompleted);
        }


        /// <summary>
        /// 读取银行list
        /// </summary>
        private void loadBank()
        {
            bankSer.GetListByHQLAsync("From Company");
        }

        // <summary>
        /// 读取操作员list（用权限判断）
        /// </summary>
        private void loadOper()
        {
            string orgNumber = AppGlobal.CurrentUser.Organization.FullNumber;
            string orgChildNumber = orgNumber + ".%";
            //获取当前机构下的操作员（具有催收权限）
            string sql = string.Format(
                        @" select u.Id,u.Name
                            from User_User as u 
                            left join User_Role as r on u.RoleId=r.Id
                            left join Organization_Organization org on u.OrganizationId = org.Id
                            where 
                                u.isused=1  and 
                                (org.FullNumber like '{0}' or org.FullNumber = '{1}') and 
                                exists(select 1 from User_Role_Right as rr 
                                            inner join User_Right as ur on rr.RightId=ur.Id 
                                        where ur.Number='process_case' and
                                rr.RoleId=r.Id) ", orgChildNumber, orgNumber);

            userSer.GetListBySQLAsync(sql);
        }

        IList<DunLibrary.Client.Company> bankList;
        void bankSer_GetListByHQLCompleted(object sender, BankService.GetListByHQLCompletedEventArgs e)
        {
            int total = 0;
            bankList = JsonSerializerHelper.JsonToEntities<DunLibrary.Client.Company>(e.Result, out total);
            //取出银行分类（非支行）
            cboxBank.ItemsSource = bankList;

        }

        void userSer_GetListBySQLCompleted(object sender, UserService.GetListBySQLCompletedEventArgs e)
        {
            int total = 0;
            var objList = JsonSerializerHelper.JsonToEntities<object[]>(e.Result, out total);
            List<UserModel> userList = objList.Select(c => new UserModel
            {
                Id = int.Parse(c[0].ToString()),
                Name = c[1].ToString()
            }).ToList();

            cboxOper.ItemsSource = userList;

            if (AppGlobal.CurrentUser.Role.Name == "业务员")
            {
                var item = userList.SingleOrDefault(c => c.Id == AppGlobal.CurrentUser.Id);
                if (item != null)
                {
                    cboxOper.SelectedItem = item;
                    cboxOper.IsEnabled = false;
                }
            }
        }


        // 当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            if (timePeriod.SelectedDate == null)
            {
                Tools.ShowMessage("请选择数据期号!", "", false);
                return;
            }

            if (tbIdCard.Value != null && !string.IsNullOrEmpty(tbIdCard.Value.ToString()))
            {
                string NumericOrLetter = "^[A-Za-z0-9]+$";
                if (!Regex.IsMatch(tbIdCard.Value.ToString(), NumericOrLetter))
                {
                    Tools.ShowMessage("‘身份证号码’输入格式错误!", "只能输入数字和字母!", false);
                    tbIdCard.Value = null;
                    return;
                }
            }

            if (cboxOper.SelectedItem == null && !string.IsNullOrEmpty(cboxOper.Text))
            {
                Tools.ShowMessage("任务负责人输入错误!", "", false);
                return;
            }

            if (cboxBank.SelectedItem == null && !string.IsNullOrEmpty(cboxBank.Text))
            {
                Tools.ShowMessage("银行分类输入错误!", "", false);
                return;
            }

            DateTime selected = timePeriod.SelectedDate.Value;
            int period = int.Parse(selected.ToString("yyyyMM"));

            int? import = null;
            if (timeImport.SelectedDate != null)
                import = int.Parse(timeImport.SelectedDate.Value.ToString("yyyyMMdd"));

            string arrealDiffStart = null;
            if (delayStart.Value != null)
                arrealDiffStart = delayStart.Value.ToString();

            string arrealDiffEnd = null;
            if (delayEnd.Value != null)
                arrealDiffEnd = delayEnd.Value.ToString();


            double? arrealAmountStart = null;
            if (amountStart.Value != null)
            {
                double val = double.Parse(amountStart.Value.ToString());
                if (val > 0.0)
                    arrealAmountStart = val;
            }

            double? arrealAmountEnd = null;
            if (amountEnd.Value != null)
            {
                double val = double.Parse(amountEnd.Value.ToString());
                if (val > 0.0)
                    arrealAmountEnd = val;
            }

            if (arrealAmountStart != null && arrealAmountEnd != null)
            {
                if (arrealAmountEnd < arrealAmountStart)
                {
                    Tools.ShowMessage("‘欠费金额’输入错误!", "最大金额必须大于最小金额!", false);
                    amountStart.Value = amountEnd.Value = null;
                    amountStart.Focus();
                    return;
                }
            }

            int? operId = null;
            if (cboxOper.SelectedItem != null)
                operId = int.Parse(cboxOper.SelectedValue.ToString());

            string cardNo = null;
            if (tbCardNo.Value != null)
                cardNo = tbCardNo.Value.ToString();

            string holderName = null;
            if (tbName.Value != null)
                holderName = tbName.Value.ToString();

            string idCard = null;
            if (tbIdCard.Value != null)
                idCard = tbIdCard.Value.ToString();

            int? bankId = null;
            if (cboxBank.SelectedItem != null)
                bankId = (cboxBank.SelectedItem as DunLibrary.Client.Company).Id;

            string orgNum = null;
            if (AppGlobal.CurrentUser.Organization != null)
                orgNum = AppGlobal.CurrentUser.Organization.FullNumber;
            Tools.ShowMask(true);
            ser.ExcelPageAsync(period,import, arrealDiffStart, arrealDiffEnd, arrealAmountStart, arrealAmountEnd, operId, cardNo, holderName,
                idCard, bankId, orgNum);

        }

        void ser_ExcelPageCompleted(object sender, ReportService.ExcelPageCompletedEventArgs e)
        {
            int total = 0;
            var list = JsonSerializerHelper.JsonToEntities<DunLibrary.Report.ExcelPage>(e.Result, out total);
            RadGridView1.ItemsSource = list;
            Tools.ShowMask(false);
        }

        /// <summary>
        /// 重置所有查询条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            timePeriod.SelectedDate = DateTime.Now;
            timePeriod.Culture.DateTimeFormat.ShortDatePattern = "yyyy-MM";

            delayStart.Value = delayEnd.Value = null;

            amountStart.Value = amountEnd.Value = null;

            if (cboxOper.SelectedItem != null)
                cboxOper.SelectedItem = null;
            else
                cboxOper.Text = null;

            tbCardNo.Value = null;
            tbName.Value = null;
            tbIdCard.Value = null;

            if (cboxBank.SelectedItem != null)
                cboxBank.SelectedItem = null;
            else
                cboxBank.Text = null;

            

            RadGridView1.ItemsSource = null;
        }

        

        private void allSelect_Click(object sender, RoutedEventArgs e)
        {
            RadGridView1.SelectAll();
        }

        private void noneSelect_Click(object sender, RoutedEventArgs e)
        {
            RadGridView1.UnselectAll();
        }

        bool? res = false;
        SaveFileDialog dialog = null;
        private void DunState_Click(object sender, RoutedEventArgs e)
        {
            if (RadGridView1.SelectedItems.Count == 0)
            {
                Tools.ShowMessage("请选择要生成‘催收情况表’的记录", "", false);
                return;
            }

            string extension = "doc";

            string selectedItem = "Word";

            dialog = new SaveFileDialog();
            dialog.DefaultExt = extension;
            dialog.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, selectedItem);

            dialog.FilterIndex = 1;
            res = dialog.ShowDialog();

            if (res == true)
            {
                var item = RadGridView1.SelectedItems[0] as DunLibrary.Report.ExcelPage;
                

                ser.DunStateAsync(item.ArId);
            }
        }

        void ser_DunStateCompleted(object sender, ReportService.DunStateCompletedEventArgs e)
        {
            var obj = JsonSerializerHelper.JsonToEntity<DunLibrary.Report.DunState>(e.Result);
            List<string> strList = new List<string>();

            var q = from grp in obj.Details
                        group grp by new
                            {
                                CallTimeStr = grp.CallTime.ToString("yyyyMMdd")
                            }
                        into g
                        select g;
            List<DunLibrary.Report.DunStateDetail> l = new List<DunLibrary.Report.DunStateDetail>();
            foreach (var group in q.OrderBy(c=>int.Parse(c.Key.CallTimeStr)))
            {
                var detail = new DunLibrary.Report.DunStateDetail();
                detail.CallTimeStr = group.Key.CallTimeStr;
                detail.Description =  obj.OperName + "：" + string.Join("<br>",
                                    group.OrderBy(c => c.CallTime).Select(item => string.Format("{0}，{1}{2}",
                                            item.PhoneNumber,
                                            item.ReceiveType,
                                            string.IsNullOrEmpty(item.CallContent) ? "；" : string.Format("，（{0}）；", item.CallContent))));
                l.Add(detail);

            }
            obj.Details = l;
            strList.Add(generateReport(obj));
            

            using (Stream stream = dialog.OpenFile())
            {
                string br = "<span lang=\"EN-US\" style=\"font-size: 12.0pt; line-height: 150%; font-family: &quot;Times New Roman&quot;,&quot;serif&quot;\"><br clear=\"all\" style=\"page-break-before: always\"></span>";
                string body = string.Join(br, strList);

                Assembly assembly = GetType().Assembly;

                string html = string.Empty;
                using (System.IO.Stream htmlStream = assembly.GetManifestResourceStream("DunSilverlight.Template.DunState.htm"))
                {
                    byte[] bsHtml = new byte[htmlStream.Length];
                    htmlStream.Read(bsHtml, 0, (int)htmlStream.Length);
                    int len = 0;// Encoding.UTF8.GetPreamble().Length;
                    html = Encoding.UTF8.GetString(bsHtml, len, bsHtml.Length - len);
                }

                html = html.Replace("@t_body", body);

                byte[] bs = Encoding.UTF8.GetBytes(html);
                string a = Encoding.UTF8.GetString(bs, 0, bs.Length);
                stream.Write(bs, 0, bs.Length);
                stream.Flush();
            }
        }


        /// <summary>
        /// 生成报告
        /// </summary>
        private string generateReport(DunLibrary.Report.DunState obj)
        {
            Assembly assembly = GetType().Assembly;

            string entity = string.Empty;
            using (System.IO.Stream entityStream = assembly.GetManifestResourceStream("DunSilverlight.Template.DunStateEntity.htm"))
            {
                byte[] bsEntity = new byte[entityStream.Length];
                entityStream.Read(bsEntity, 0, (int)entityStream.Length);
                int len = 0;// Encoding.UTF8.GetPreamble().Length;
                entity = Encoding.UTF8.GetString(bsEntity, len, bsEntity.Length - len);
            }

            string head = string.Empty;

            using (System.IO.Stream headStream = assembly.GetManifestResourceStream("DunSilverlight.Template.DunStateHead.htm"))
            {
                byte[] bsHead = new byte[headStream.Length];
                headStream.Read(bsHead, 0, (int)headStream.Length);
                int len = 0;// Encoding.UTF8.GetPreamble().Length;
                head = Encoding.UTF8.GetString(bsHead, len, bsHead.Length - len);

            }

            head = head.Replace("@t_org", "迪扬");
            head = head.Replace("@t_createDate", DateTime.Now.ToString("yyyy-MM-dd"));
            head = head.Replace("@t_docPerson", obj.OperName);
            head = head.Replace("@t_holderName", obj.HolderName);
            head = head.Replace("@t_cardNo", obj.CardNo);
            head = head.Replace("@t_idCard", obj.IdCard);
            head = head.Replace("@t_homeAddress", obj.HomeAddress);
            head = head.Replace("@t_homeTel", obj.HomePhone);
            head = head.Replace("@t_homePostCode", obj.HomePostcode);
            head = head.Replace("@t_companyAddress", obj.CompanyAddress);
            head = head.Replace("@t_companyName", obj.CompanyName);
            head = head.Replace("@t_companyPostCode", obj.CompanyPostcode);
            head = head.Replace("@t_companyTel", obj.CompanyPhone);
            head = head.Replace("@t_mobile", obj.Mobile);

            head = head.Replace("@t_cardDelayLevel", obj.CardDelayLevel);
            head = head.Replace("@t_totalDiff", obj.AmountNotPay.ToString());

            entity = entity.Replace("@t_head", head);

            string details = string.Empty;
            using (System.IO.Stream detailStream = assembly.GetManifestResourceStream("DunSilverlight.Template.DunStateDetail.htm"))
            {
                byte[] bsDetail = new byte[detailStream.Length];
                detailStream.Read(bsDetail, 0, (int)detailStream.Length);
                int len = 0;// Encoding.UTF8.GetPreamble().Length;
                details = Encoding.UTF8.GetString(bsDetail, len, bsDetail.Length - len);
            }
            StringBuilder sb = new StringBuilder();
            foreach (var item in obj.Details)
            {
                sb.Append(details.Replace("@t_callTime", item.CallTimeStr).Replace("@t_Description", item.Description));
            }



            entity = entity.Replace("@t_details", obj.Details.Count > 0 ? sb.ToString() : "");

            return entity;


        }

        private void date_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btnQuery_Click(sender, null);
            }
        }
       
    }
}
